import baostock as bs
import pandas as pd
import pymysql
from DBUtils.PooledDB import PooledDB

#数据库连接池配置
POOL = PooledDB(
    creator=pymysql,  # 使用链接数据库的模块
    maxconnections=6,  # 连接池允许的最大连接数，0和None表示不限制连接数
    mincached=2,  # 初始化时，链接池中至少创建的空闲的链接，0表示不创建
    maxcached=5,  # 链接池中最多闲置的链接，0和None不限制
    blocking=True,  # 连接池中如果没有可用连接后，是否阻塞等待。True，等待；False，不等待然后报错
    maxusage=None,  # 一个链接最多被重复使用的次数，None表示无限制
    setsession=[],  # 开始会话前执行的命令列表。如：["set datestyle to ...", "set time zone ..."]
    ping=0,
    # ping MySQL服务端，检查是否服务可用。# 如：0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
    host='120.55.183.30',
    port=3306,
    user='root',
    password='AAbb147258',
    database='luckystock',
    charset='utf8',
    autocommit='True'
)

#采集历史数据
def fetchHistory(code):
    if code.startswith("3") or code.startswith("0"):
        type = "sz"
    else:
        type = "sh"

    #### 登陆系统 ####
    lg = bs.login()
    # 显示登陆返回信息
    print('login respond error_code:'+lg.error_code)
    print('login respond  error_msg:'+lg.error_msg)

    #### 获取沪深A股历史K线数据 ####
    # 详细指标参数，参见“历史行情指标参数”章节；“分钟线”参数与“日线”参数不同。“分钟线”不包含指数。
    # 分钟线指标：date,time,code,open,high,low,close,volume,amount,adjustflag
    # 周月线指标：date,code,open,high,low,close,volume,amount,adjustflag,turn,pctChg
    strCode = "{type}.{code}".format(type = type, code = code)
    rs = bs.query_history_k_data_plus(strCode,
                                      "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,isST",
                                      start_date='2020-01-01', end_date='2023-11-17',
                                      frequency="d", adjustflag="3")
    print('query_history_k_data_plus respond error_code:'+rs.error_code)
    print('query_history_k_data_plus respond  error_msg:'+rs.error_msg)

    #### 打印结果集 ####
    data_list = []
    while (rs.error_code == '0') & rs.next():
        # 获取一条记录，将记录合并在一起
        data_list.append(rs.get_row_data())
    result = pd.DataFrame(data_list, columns=rs.fields)

    #### 结果集输出到csv文件 ####
    result.to_csv("D:\my\history\{}.csv".format(code), index=False)
    print(result)

    #### 登出系统 ####
    bs.logout()

# 获取所以代码
def getStockCodeList():
    conn = POOL.connection()
    cursor = conn.cursor()
    result = []
    cursor.execute("select code from stock_stock")
    values = cursor.fetchall()
    if len(values):
        for value in values:
            code = value[0]
            result.append(code)
    return result

# main方法
if __name__ == "__main__":
    codeList = getStockCodeList()
    for code in codeList:
        print(code)
        fetchHistory(code)

